package com.an.java.javaall.suafa;

public class Sort {

    public static void bubbleSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = 0; j < a.length - 1 - i; j++) {
                if (a[j] > a[j + 1]) {
                    int tmp = a[j + 1];
                    a[j + 1] = a[j];
                    a[j] = tmp;
                }
            }
        }
    }

    //选择排序
    public static void selectSort(int[] a) {
        int minIdex;
        int tmp;
        for (int i = 0; i < a.length - 1; i++) {
            minIdex = i;
            for (int j = i + 1; j < a.length; j++) {
                if (a[j] < a[minIdex]) {
                    minIdex = j;
                }
            }
            tmp = a[i];
            a[i] = a[minIdex];
            a[minIdex] = tmp;
        }
    }

    /**
     * 插入排序
     *
     * @param a
     */
    public static void insertSort(int[] a) {
        for (int i = 1; i < a.length; i++) {
            int target = a[i];
            int preIndex = i - 1;
            while (preIndex >= 0 && target < a[preIndex]) {
                a[preIndex + 1] = a[preIndex];
                preIndex--;
            }
            a[preIndex + 1] = target;
        }
    }

    /**
     * 希尔排序
     *
     * @param a
     */
    public static void shellSort(int[] a) {
        for (int gap = Math.floorDiv(a.length, 2); gap > 0; gap = Math.floorDiv(gap, 2)) {
            for (int i = gap; i < a.length; i++) {
                int j = i;
                int current = a[i];
                while (j - gap >= 0 && current < a[j - gap]) {
                    a[j] = a[j - gap];
                    j = j - gap;
                }
                a[j] = current;
            }
        }
    }

    public static void shellSort2(int[] a) {
        if(null == a || a.length == 1) {
            return;
        }
        for (int gap = a.length / 2; gap >0 ; gap /= 2) {
            for (int i = gap; i < a.length; i++) {
                int j = gap;
                int current = a[i];
                while (j - gap >= 0 && current < a[j - gap]) {
                    a[j] = a[j - gap];
                    j = j - gap;
                }
                a[j] = current;
            }
        }
    }
}
